// 兼容在IE浏览器导出的安装包
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
import Browser from './browser'

export function exportJson(fileName, content) {
  var data = JSON.stringify(content)
  var blob = new Blob([data], { type: '' })
  FileSaver.saveAs(blob, fileName + '.json')
}

export function exportExcel(exportHeader, data, fileName) {
  // 参数格式
  // exportHeader  对象 {name:'姓名',age:'年龄',sex:'性别'} 
  // data 数组 [{name:'小明',age:'18',sex:'男'}]
  // 将data转化为[{姓名:'小明',年龄:'18',性别:'男'}]
  data.forEach(item => {
    for (let i in item) {
      if (item[i]) {
        item[exportHeader[i]] = item[i].toString()
      }
      delete item[i] // 删除原先的对象属性
    }
  })
  let s2ab = s => {
    if (typeof ArrayBuffer !== 'undefined') {
      let buf = new ArrayBuffer(s.length)
      let view = new Uint8Array(buf)
      for (let i = 0; i < s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
      return buf
    } else {
      let buf = new Array(s.length)
      for (let i = 0; i < s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF
      return buf
    }
  }
  let wb = XLSX.utils.book_new() // 工作簿对象包含一SheetNames数组，以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。
  let ws = XLSX.utils.json_to_sheet(data, { header: Object.values(exportHeader) }) // 将JS对象数组转换为工作表。
  wb.SheetNames.push(fileName)
  wb.Sheets[fileName] = ws
  let defaultCellStyle = {
    font: { name: 'Verdana', sz: 13, color: 'FF00FF88' },
    fill: { fgColor: { rgb: 'FFFFAA00' } }
  }// 设置表格的样式
  let wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary',
    cellStyles: true,
    defaultCellStyle: defaultCellStyle,
    showGridLines: false
  } // 写入的样式
  let wbout = XLSX.write(wb, wopts)
  let blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })
  FileSaver.saveAs(blob, fileName + '.xlsx')
}

export function exportByUrl(url) {
  let browser = new Browser()
  // 兼容IE浏览器下载
  if (browser.browser === 'IE') {
    var oPop = window.open(url, '', 'width=1, height=1, top=5000, left=5000')
    for (; oPop.document.readyState !== 'complete';) {
      if (oPop.document.readyState === 'complete') {
        break
      }
    }
    oPop.document.execCommand('SaveAs')
    oPop.close()
  } else {
    var aLink = document.createElement('a')
    document.body.appendChild(aLink)
    aLink.href = url
    aLink.setAttribute('download', '')
    aLink.click()
    document.body.removeChild(aLink)
  }
  // FileSaver.saveAs(url)
}
